<?php
// 应用公共文件

function getServices($name){
    return new $name(getSystem());
}

function getSystem(){
    $system = \think\facade\Config::get('system');
    if(empty($system[$_SERVER['HTTP_HOST']])) {
        throw new \app\CustomException('缺少配置HOST参数！', 500);
    }
    return $system[$_SERVER['HTTP_HOST']];
}


function getCacheTime(){
   $nowTime = time();
   $ktime = strtotime(date('Y-m-d 21:30:00',time()));
   $ktime1 = strtotime(date('Y-m-d 22:30:00',time()));
   $ktime3 = strtotime(date('Y-m-d 10:00:00',time()));
   $ktime4 = strtotime(date('Y-m-d 00:00:00',time()));
   
   //10:30 - 21:30之间
    if($nowTime < $ktime && $nowTime > $ktime3) {
        return $ktime - $nowTime;
    }
    //在21点30 - 21点35之间时 缓存30秒
    else if ($nowTime >= $ktime && $nowTime < ($ktime + 300)) {
        return 30;
    }//21点35 - 22:30之间时
    else if ($nowTime >= ($ktime+300) && $nowTime < $ktime1) {
        return $ktime1 - $nowTime;
    }else if ($nowTime >= $ktime1 && $nowTime < ($ktime1+300)) {
        return 30;
    }//22:30以后 - 次日0:0
    else if($nowTime >= $ktime1 && $nowTime < ($ktime4 +86400)) {
        return ($ktime3 +86400) - $nowTime;
    }else if($nowTime >= $ktime4 && $nowTime < $ktime3){
        return $ktime3 - $nowTime;
    }else {
        return 30;
    }
}


/**
 * 时间戳 - 精确到毫秒
 * @return float
 */
function getMillisecond()
{
    [$t1, $t2] = explode(' ', microtime());
    return (float)sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
}

/**
     * 检测当前控制器和方法是否匹配传递的数组
     *
     * @param array $arr 需要验证权限的数组
     */
    function matchArr(array $arr, string $action): ?bool
    {
        if (empty($arr)) {
            return false;
        }
        // 是否存在
        if (in_array($action, $arr) || in_array('*', $arr)) {
            return true;
        }
        // 没找到匹配
        return false;
    }

     /**
     * 获取签名串
     * @param array $data
     * @return type
     */
    function getSign(array $arr,?string $appkey=null,?string $appsecret=null)
    {
        if (empty($arr)) {
            return null;
        }

        $appkey = !empty($appkey) ? $appkey : md5('37DE229506983BC6');
        $appsecret = !empty($appsecret) ? $appsecret : 'E0DF78D7A5A22562B58C43537A288C99';
        
        $data = filterArray($arr);
        $data['appkey']       = $appkey;
        $data['appsecret']    = $appsecret;
        ksort($data);
        //组装加密串
        $str = json_encode($data, JSON_UNESCAPED_UNICODE) . $data['appsecret'];
        return md5(md5($str) . $data['appkey']);
    }
    
    /**
     * Undocumented function
     * 过滤数组
     * @param array $data
     * @return array
     */
    function filterArray(array $data):array 
    {
        $arr = [];
        foreach ($data as $k => $v) {
            if (!is_array($v)) {
                $arr[$k] = urlencode($v);
            }
        }

        return $arr;
    }

    /**
     * 加密
     */
    function encrypt($data = array(), $sig = "")
    {
        //AES, 128 ECB模式加密数据
        if (empty($data) || empty($sig)) {
            return null;
        }
        $input = json_encode($data, JSON_UNESCAPED_UNICODE);


        //0~8 + -16~-8
        $key = substr($sig, 0, 8) . substr($sig, 16, 8);
        //8~8 + -8~16
        $iv    = substr($sig, 8, 8) . substr($sig, 24, 8);

        $data = openssl_encrypt($input, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
        $data = rawurlencode(base64_encode($data));

        return $data;
    }



    /**
     * 解密
     */
    function decrypt(string $input = '', $sig = "")
    {
        if (empty($input) || empty($sig)) {
            return null;
        }

        //0~8 + -16~-8
        $key = substr($sig, 0, 8) . substr($sig, 16, 8);
        //8~8 + -8~16
        $iv    = substr($sig, 8, 8) . substr($sig, 24, 8);

        $decrypted = openssl_decrypt(base64_decode(rawurldecode($input)), "AES-128-CBC", $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv);

        return preg_replace('/[\x00-\x1F]/', '', $decrypted);
    }


    /**
     * Undocumented function
     * 组合路径
     * @param string $dir
     * @param string $path
     * @return string
     */
    function combinationPath(string $dir, string $path): string
    {
        
        if (!empty($dir)) {
            if (substr($dir, -1) !== '/') {
                $dir .= '/';
            }
            if (substr($path, 0, 1) === '/') {
                $path = substr($path, 1, strlen($path) - 1);
            }
        }

        return $dir . $path;
    }

//过滤参数
function filtParams(string $str){
    //htmlspecialchars函数可将特殊字符转换为HTML实体，防止XSS攻击
    $str = htmlspecialchars($str);
    //strip_tags函数可去除字符串中的HTML标签
    $str = strip_tags($str);
    //addslashes函数可对字符串进行反斜线转义处理，主要用于SQL语句等场景。
    $str = addslashes($str);
    return $str;
}


function getFormUniqid(){
    return md5(md5(uniqid(rand())));
}


/**
 * Tag类型获取缓存
 */
function getTagCache(string $tag,?string $name=null){
    $list = \think\facade\Cache::get($tag);
    if($name === null) {
        $arr = [];
        foreach($list as $k=>$v) {
            $val = unserialize($v);
            if(!empty($val['tagCacheName'])) {
                $arr[] = $val['tagCacheName'];
            }else{
                $arr[] = $val;
            }
            
        }
        return $arr;
    }
    $value = null;
    if(!empty($list[$name])) {
        $value = unserialize($list[$name]);
    }
    if(empty($value)) {
        return null;
    }

    if(array_key_exists('tagCacheName',$value)) {
        return $value['tagCacheName'];
    }
    
    return $value;
}


/**
 * Tag类型设置缓存
 */
function setTagCache(string $tag,string $name, $value,int $time=0){
    $str = '';
    if(is_array($value) || is_object($value)) {
        $str = serialize($value);
    }else{
        $str = serialize(['tagCacheName'=>$value]);
    }

    $cacheData = \think\facade\Cache::get($tag);
    if(empty($cacheData)) {
        $cacheData = [];
    }
    $cacheData[$name] = $str;  
    \think\facade\Cache::set($tag,$cacheData,$time);

    return true;
}


/**
 * Tag类型清空缓存
 */
function clearTagCache(string $tag){
    \think\facade\Cache::delete($tag);
}



/**
 * 获取系统接口域名
 * @return string
 */
function siteUrl()
{
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $domainName = $_SERVER['HTTP_HOST'];
    return $protocol . $domainName;
}



function model($class){
    return new $class();
}